import { Button } from "antd";
import { SendOutlined } from "@ant-design/icons";
import {
  Table,
  Modal,
  DatePicker,
  Select,
  Button as ArcoButton,
  Message,
  Notification,
} from "@arco-design/web-react";
import { memo, useEffect, useState } from "react";
import { TableWrapper, TaskModificationWrapper } from "./style";
import { useAppDispatch, useAppSelector } from "../../../../store";
import { fetchUpdateTaskAction } from "../../../../store/modules/patient";
import dayjs from "dayjs";

interface TaskModificationProps {
  userId: number;
  getDataFn: (params: { userId: number }) => void;
}

const TaskModification = ({ userId, getDataFn }: TaskModificationProps) => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const [visible, setVisible] = useState(false);
  const [tasks, setTasks] = useState<
    {
      key?: number | null;
      taskId?: number | null;
      title?: string | null;
      timeOn?: string | null;
      deadline?: string | null;
      state?: string | null;
    }[]
  >([]);
  const [pastTask, setPastTask] = useState<
    {
      key: number | null;
      taskId: number | null;
      title: string | null;
      timeOn: string | null;
      deadline: string | null;
      state: string | null;
    }[]
  >([]);
  const dispatch = useAppDispatch();

  const { taskList, modificationAndTaskList } = useAppSelector(
    (state) => state.patient
  );
  //?state改变ui视图
  useEffect(() => {
    if (modificationAndTaskList) {
      const pastTasks = modificationAndTaskList?.tasksVO
        ?.filter((item: any) => {
          return item.state === "3" || item.state === "2" || item.state === "1";
        })
        .map((item: any) => {
          return {
            key: item.id, //主键id
            taskId: item.taskId,
            state: item.state,
            timeOn: item.timeOn,
            deadline: item.deadline,
            title: item.title,
          };
        });
      setPastTask(pastTasks);
      const currentTasks = modificationAndTaskList?.tasksVO
        ?.filter((item: any) => {
          return item.state === "0" || item.state === null;
        })
        .map((item: any) => {
          return {
            key: item.id, //主键id
            taskId: item.taskId,
            state: item.state,
            timeOn: item.timeOn,
            deadline: item.deadline,
            title: item.title,
          };
        });
      setTasks(currentTasks);
    }
  }, [modificationAndTaskList]);
  const toggleModal = (target: boolean) => {
    if (target && getDataFn && userId) {
      getDataFn({ userId }); // 在打开模态框时调用 onOpen 并传递 userId
    }
    setVisible(target);
  };

  const nowData = tasks;
  const pastData = pastTask;

  const pastColums = [
    {
      title: "检查任务",
      dataIndex: "title",
      key: "title",
      render: (value: number, record: any, index: number) => {
        console.log(record);
        return (
          <Select
            disabled
            placeholder="请选择检查项目"
            value={record.taskId || null}
            style={{ width: "250px" }}
            // onChange={(newValue) => handleExaminationChange(index, newValue)}
          >
            {taskList?.map((item: any) => {
              return (
                <Select.Option value={item.id} key={item.id}>
                  {item.title}
                </Select.Option>
              );
            })}
          </Select>
        );
      },
    },
    {
      title: "状态",
      dataIndex: "state",
      key: "state",
      render: (value: string, record: any, index: number) => {
        if (value === "0") return <span>未开始</span>;
        if (value === "1") return <span>已完成</span>;
        if (value === "2") return <span>已逾期</span>;
        if (value === "3") return <span>逾期未完成</span>;
      },
    },
    {
      title: "时间",
      dataIndex: "time",
      key: "time",
      render: (time: string, record: any, index: number) => {
        return (
          <DatePicker.RangePicker
            disabled
            placeholder={["请输入开始时间", "请输入结束时间"]}
            style={{ width: "300px" }}
            value={
              record.timeOn && record.deadline
                ? [record.timeOn, record.deadline]
                : [null, null]
            }
            format="YYYY年MM月DD日"
          />
        );
      },
    },
  ];
  const nowColums = [
    {
      title: "检查任务",
      dataIndex: "title",
      key: "title",
      render: (value: number, record: any, index: number) => {
        // console.log(record);
        return (
          <Select
            placeholder="请选择检查项目"
            value={record.taskId || null}
            style={{ width: "250px" }}
            onChange={(newValue) => handleTaskChange(index, newValue)}
          >
            {taskList?.map((item: any) => {
              return (
                <Select.Option value={item.id} key={item.id}>
                  {item.title}
                </Select.Option>
              );
            })}
          </Select>
        );
      },
    },
    {
      title: "状态",
      dataIndex: "state",
      key: "state",
      render: (value: string, record: any, index: number) => {
        if (value === "0") return <span>未开始</span>;
        if (value === "1") return <span>已完成</span>;
        if (value === "2") return <span>已逾期</span>;
        if (value === "3") return <span>逾期未完成</span>;
      },
    },
    {
      title: "时间",
      dataIndex: "time",
      key: "time",
      render: (time: string, record: any, index: number) => {
        // console.log(record);

        return (
          <DatePicker.RangePicker
            placeholder={["请输入开始时间", "请输入结束时间"]}
            style={{ width: "300px" }}
            value={
              record.timeOn && record.deadline
                ? [record.timeOn, record.deadline]
                : [null, null]
            }
            onChange={(date) => {
              console.log(date);

              const [start, end] = date;
              handleDateChange(index, start, end);
            }}
            format="YYYY年MM月DD日"
          />
        );
      },
    },
  ];
  /**
   * @表单
   */

  const handleTaskChange = (index: number, value: number) => {
    // console.log(index, value);
    setTasks((prev) => {
      const newTasks = [...prev];
      newTasks[index] = {
        ...newTasks[index],
        taskId: value,
      };
      return newTasks;
    });
  };

  const handleDateChange = (index: number, start: string, end: string) => {
    console.log(start, end);
    const formattedStart = start
      ? dayjs(start, "YYYY年MM月DD日").format("YYYY-MM-DD")
      : "";
    const formattedEnd = end
      ? dayjs(end, "YYYY年MM月DD日").format("YYYY-MM-DD")
      : "";

    setTasks((prev) => {
      const newTasks = [...prev];
      newTasks[index] = {
        ...newTasks[index],
        timeOn: formattedStart,
        deadline: formattedEnd,
      };
      return newTasks;
    });
  };
  // console.log(tasks);

  /**
   * @footer按钮相关操作
   */

  /**
   * @新增
   */
  const newAddTask = () => {
    setTasks((prev) => [
      ...prev,
      {
        key: Date.now(),
        state: null,
        taskId: null,
        deadline: null,
        timeOn: null,
      },
    ]);
  };

  /**
   * @单选框列表
   */
  const onSelectChange = (newSelectedRowKeys: any) => {
    console.log("selectedRowKeys changed: ", newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    checkAll: false,
    onChange: onSelectChange,
  };
  /**
   * @删除按钮
   */

  const deleteSelection = () => {
    if (selectedRowKeys.length === 0) {
      Message.warning("请先选择要删除的项");
      return;
    }
    const id = `${Date.now()}`;
    Notification.error({
      id,
      title: "警告",
      content: "确定要删除这条数据吗",
      btn: (
        <span>
          <ArcoButton
            type="secondary"
            size="small"
            onClick={() => {
              Notification.remove(id);
              setSelectedRowKeys([]);
            }}
            style={{ margin: "0 12px" }}
          >
            取消
          </ArcoButton>
          <ArcoButton
            type="primary"
            size="small"
            onClick={() => {
              setTasks((prev) =>
                prev.filter((item) => !selectedRowKeys.includes(item.key))
              );
              setSelectedRowKeys([]);
              // Message.success("删除成功");
              Notification.remove(id);
              Message.info("点击完以后再点击确认按钮即可删除");
            }}
          >
            确认
          </ArcoButton>
        </span>
      ),
    });
  };
  /**
   * @提交
   */
  const handleSubmitTask = async () => {
    const body = {
      examinationList: [],
      examinationListUpdate: [],
      taskList: tasks.map((item) => {
        return {
          id: item.taskId || null,
          state: "0",
          timeOn: item.timeOn || null,
          deadline: item.deadline || null,
        };
      }),
      userId: userId,
      taskListUpdate: [],
    };
    await dispatch(fetchUpdateTaskAction(body));
    toggleModal(false);
  };
  return (
    <TaskModificationWrapper>
      <Button
        icon={<SendOutlined />}
        size="small"
        type="link"
        style={{ gap: "3px", width: "50px", height: "14px" }}
        onClick={() => toggleModal(true)}
      >
        任务修改
      </Button>
      <Modal
        style={{ width: "800px" }}
        title="检查修改"
        visible={visible}
        onOk={() => toggleModal(false)}
        onCancel={() => toggleModal(false)}
        autoFocus={false}
        focusLock={true}
        footer={
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              gap: "10px",
            }}
          >
            <Button key="newAdd" onClick={newAddTask}>
              新增
            </Button>
            <Button key="delete" onClick={deleteSelection}>
              删除选中
            </Button>
            <Button key="cancel" onClick={() => setVisible(false)}>
              取消
            </Button>
            <Button type="primary" key="sure" onClick={handleSubmitTask}>
              确定
            </Button>
          </div>
        }
      >
        <TableWrapper>
          <Table
            columns={pastColums}
            data={pastData}
            pagination={false}
            style={{ userSelect: "none", height: "250px", overflowY: "auto" }}
          />
          <Table
            rowSelection={rowSelection}
            columns={nowColums}
            data={nowData}
            style={{ userSelect: "none", height: "240px", overflowY: "auto" }}
            pagination={false}
          />
        </TableWrapper>
      </Modal>
    </TaskModificationWrapper>
  );
};
export default memo(TaskModification);
